﻿using log4net;
using log4net.Config;
using MyServer.Code;
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace MyServer
{
    public partial class FormMain : Form
    {
        /// <summary>
        /// 日志
        /// </summary>
        public static ILog logger = null;
        /// <summary>
        /// UI委托
        /// </summary>
        private delegate void AsynUpdateUI(object args);
        /// <summary>
        /// 计时器
        /// </summary>
        private System.Timers.Timer timer = null;

        public FormMain()
        {
            InitializeComponent();
            InitLog();

            timer.StartTimer(TimerCheckUI, 100);
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            labelIP.Text = "IP地址：" + Tool.GetLocalIP();
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            CloseLog();

            timer.CloseTimer(TimerCheckUI);
            MySocketManager.Instance.ServerClose();
        }

        /// <summary>
        /// 启动服务器按钮
        /// </summary>
        private void buttonStart_Click(object sender, EventArgs e)
        {
            int port = 0;
            int.TryParse(textBoxPort.Text, out port);

            MySocketManager.Instance.ServerStart(port);
        }

        /// <summary>
        /// 关闭服务器按钮
        /// </summary>
        private void buttonClose_Click(object sender, EventArgs e)
        {
            MySocketManager.Instance.ServerClose();
        }

        /// <summary>
        /// 清空日志按钮
        /// </summary>
        private void buttonClear_Click(object sender, EventArgs e)
        {
            listBoxLog.Items.Clear();
        }

        /// <summary>
        /// 定期检测是否连接
        /// </summary>
        private void TimerCheckUI(object source, System.Timers.ElapsedEventArgs e)
        {
            MySocketManager manager = MySocketManager.Instance;
            
            if (InvokeRequired)
            {
                Invoke(new AsynUpdateUI(delegate (object o)
                {
                    bool run = (bool)o;
                    ChangeStateByIsRunning(run);
                }), manager.IsRunning);
            }
            else
            {
                ChangeStateByIsRunning(manager.IsRunning);
            }
        }

        /// <summary>
        /// 根据服务器是否运行改变UI状态
        /// </summary>
        /// <param name="isRunning">服务器是否运行</param>
        private void ChangeStateByIsRunning(bool isRunning)
        {
            labelState.ForeColor = isRunning ? Color.Green : Color.Red;
            labelState.Text = isRunning ? "运行中" : "未启动";
            buttonStart.Enabled = !isRunning;
            buttonClose.Enabled = isRunning;
        }

        /// <summary>
        /// 初始化日志
        /// </summary>
        private void InitLog()
        {
            FileInfo logConfig = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config");
            XmlConfigurator.ConfigureAndWatch(logConfig);
            logger = LogManager.GetLogger(typeof(Program));

            MyEventManager.Instance.Register(MyEvent.日志, LogEvent);
        }

        /// <summary>
        /// 关闭日志
        /// </summary>
        private void CloseLog()
        {
            logger = null;

            MyEventManager.Instance.UnRegister(MyEvent.日志, LogEvent);
        }

        /// <summary>
        /// 事件通知输出日志
        /// </summary>
        private void LogEvent(params object[] args)
        {
            string log = args[0].ToString();
            bool isRecord = (bool)args[1];
            Log(log, isRecord);
        }

        /// <summary>
        /// 主界面输出日志
        /// </summary>
        /// <param name="log">日志</param>
        /// <param name="isRecord">是否记录在本地</param>
        private void Log(string log, bool isRecord)
        {
            if (InvokeRequired)
            {
                Invoke(new AsynUpdateUI(delegate (object o)
                {
                    listBoxLog.Items.Add(o + Environment.NewLine);
                }), log);
            }
            else
            {
                listBoxLog.Items.Add(log + Environment.NewLine);
            }

            if (isRecord)
                logger.Info(log);
        }
    }
}
